//RouterExtendProvider
define(['angularAMD', 'module/system/program/logging/logging', 'JSplugins/ModuleInstaller/sJDSInstallerService'], function (angularAMD) {
    angularAMD.factory('RouterExtendProvider', ['$rootScope', '$filter', '$timeout', 'config', '$mdDialog', 'MMWService', '$state', 'sJDSInstallerService', 'LoggingService', '$templateRequest',
    function($rootScope, $filter, $timeout, config, $mdDialog, $MMWService, $state, $sJDSInstallerService, $LoggingService, $templateRequest){
        var RouterExtendProvider = this,
            prev_state = {};
        $rootScope.menuTitle = '';
        $MMWService.needLogout = function(callback){
            // 20231002 modify by Alan for#145964 : 避免重複呼叫登出
            if (config.cache.isWaitingLogout) return;
            config.cache.isWaitingLogout = true;
            $mdDialog.closeAll(function(){
                $rootScope.hideMenu();
                config.mdssessionno = '';
                $rootScope.closeAllWindow();
                delete $rootScope.menuClick;
                //$rootScope.showAlert($filter('translate')('error.sessionTimeout'));
                $rootScope.changeProgram(RouterExtendProvider.login_page, true);
                if(callback){
                    callback();
                }
            });
        };
        RouterExtendProvider.login_page = 'login';
        RouterExtendProvider.home_page = 'home';
        RouterExtendProvider.setting_page = 'setting';
        // 20220613 modify by Alan for#112054 : 修改我的最愛跳轉邏輯
        RouterExtendProvider.myFavourite_page = {
            main: 'myFavourite_main',
            edit: 'myFavourite_edit'
        };
        RouterExtendProvider.sideTools = [];
        RouterExtendProvider.extendSideMenus = [];

        RouterExtendProvider.triggerSetting = function(){
            if($rootScope.currentState != RouterExtendProvider.setting_page){
                prev_state.name = $rootScope.currentState;
                prev_state.stateParams = $state.$current.locals.globals.$stateParams;
                prev_state.showMenu = $rootScope.isShowMenu;
                $rootScope.changeProgram(RouterExtendProvider.setting_page, {parent : prev_state.name, sideMenu: true});
                if ($rootScope.currentState == 'home') {
                    $rootScope.selectHome = true;
                }
            } else {
                var parent = prev_state.name;
                if(parent == undefined){
                    parent = $state.$current.locals.globals.$stateParams.parent;
                }

                $rootScope.changeProgram(parent, prev_state.stateParams, true);
                if(prev_state.showMenu){
                    $rootScope.loadMenu();
                }
                prev_state = {};
            }
        };
        
        // 20220613 modify by Alan for#112054 : 修改我的最愛跳轉邏輯
        RouterExtendProvider.myFavourite = function(mode){
            $rootScope.changeProgram(RouterExtendProvider.myFavourite_page[mode]);
        };

        // 20220615 modify by Alan for#112054 : 修改作業搜尋選擇顯示
        RouterExtendProvider.openSearchDialog = function(callback){
            $mdDialog.serviceDialog('searchDialogService', {}, callback);
        };

        RouterExtendProvider.home = function(){
            // $state.$current.locals['@'].$scope.back();
            $rootScope.selectHome = true;
            $rootScope.changeProgram(RouterExtendProvider.home_page);
        };

        $MMWService.logoutExtend = RouterExtendProvider.logout = function(callback, errorback){
            $rootScope.closeAllWindow();
            $timeout(function(){
                var paramets = {data:{notLogin:true}};
                paramets.beforeExist = function(callback){
                    $rootScope.selectHome = true;
                 
                      $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_SYS.clear_login_info_json',
                        content : {},
                        msg : 'home.msg.logouting',
                        success : function(data){
                            if(typeof(RouterExtendProvider.MailStop) == 'function')
                                RouterExtendProvider.MailStop();

                            config.mdssessionno = '';
                            if(config.cache.autoLogin){
                                try{
                                    // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                                    const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                                    remote.getCurrentWindow().close();
                                } catch(e){
                                    nodeRequire('nw.gui').Window.get().close();
                                }
                            } else {
                                $rootScope.subMenu = undefined;
                                $rootScope.hideMenu();
                            }
                            callback();
                        },
                        error:errorback
                    });

                };
                if(typeof callback == 'function')
                    paramets.beforeExist(callback);
                else
                    $rootScope.changeProgram(RouterExtendProvider.login_page, paramets, true);
            });
        };

        RouterExtendProvider.goToModule = function(menuItem, callback, failback){
            if(menuItem.module){
                //判斷是否為外部模組

                //關閉sideSubMenu
                if(typeof failback === 'function'){
                    failback();
                }

                if(menuItem.name == 'sJDS'){
                    $sJDSInstallerService.open({});
                }
            } else if(!menuItem.default && !menuItem.childs){
                //沒有設定default、沒有設定子分類

                //關閉sideSubMenu
                if(typeof failback === 'function'){
                    failback();
                }

                $rootScope.subMenu = undefined;
                $rootScope.changeProgram(menuItem.name, menuItem.data);
                $rootScope.loadMenu(config.menu);
            } else if(!menuItem.default || menuItem.name == 'modelC' ){
                //沒有設定default、有設定子分類
                $rootScope.subMenu = menuItem;
                if(menuItem.name == 'C01' || menuItem.name == 'modelC' ){
                    RouterExtendProvider.loadReportModule(menuItem, function(menuItem){
                        $rootScope.subMenu = menuItem;
                        if(typeof callback === 'function'){
                            callback(menuItem, {mode:'module'});
                        }
                    });
                }
                // 20230210 modify by Alan for#127517 : 修正自訂義報表載入
                else if(menuItem.name == 'C20' || menuItem.name == 'modelKB')
                {
                    RouterExtendProvider.loadKanbanModule(menuItem, function(menuItem){
                        $rootScope.subMenu = menuItem;
                        if(typeof callback === 'function'){
                            callback(menuItem, {mode:'module'});
                        }
                    });
                } 
                else if(typeof callback === 'function'){
                    callback(menuItem, {mode:'module'});
                }
            } else {
                //關閉sideSubMenu
                if(typeof failback === 'function'){
                    failback();
                }

                $rootScope.subMenu = undefined;
                $rootScope.changeProgram(menuItem.default, menuItem.data);
                if(!menuItem.hideMenu && $filter('filter')(menuItem.childs, {isShow:true}).length>1){
                    $rootScope.loadMenu(menuItem.childs);
                } else {
                    $rootScope.menuList = menuItem.childs;
                    $rootScope.hideMenu();
                }
            }
        };

        RouterExtendProvider.goToProgram = function(menuItem){
            if(menuItem.name == 'modelB03' || menuItem.name == 'modelB04' || menuItem.name == 'modelB10'){
                RouterExtendProvider.isSetFavorites(menuItem);
            } else if(menuItem.name == 'C01' || menuItem.name == 'modelC' ){
                RouterExtendProvider.loadReportModule(menuItem);
            // 20230210 modify by Alan for#127517 : 修正自訂義報表載入
            }else if(menuItem.name == 'C20' || menuItem.name == 'modelKB')
            {
                RouterExtendProvider.loadKanbanModule(menuItem);
            } else if(menuItem.isReport){
                RouterExtendProvider.loadReportProgram(menuItem);
            } else {
                if(!menuItem.default && menuItem.childs && menuItem.childs.length > 0){
                    menuItem.default = menuItem.childs[0].name;
                } else if(!menuItem.default){
                    menuItem.default = menuItem.name;
                }

                $rootScope.changeProgram(menuItem.default, menuItem.data);
                if(!menuItem.hideMenu && menuItem.childs && $filter('filter')(menuItem.childs, {isShow:true}).length>1){
                    $rootScope.loadMenu(menuItem.childs);
                } else {
                    $rootScope.menuList = menuItem.childs;
                    $rootScope.hideMenu();
                }
            }
        };

        //判斷是否要進入我的最愛畫面
        RouterExtendProvider.isSetFavorites = function(menuItem, callback){
            var content = {
                master_type : '0',
                get_employee_data:'Y'
            };

            if(menuItem.name == 'modelB03'){
                content.master_no = config.cache.account;
            } else if(menuItem.name == 'modelB04' || menuItem.name == 'modelB10'){
                if(config.setting.OperatingArea==''){
                    $rootScope.showAlert($filter('translate')('home.showAlert'));
                    return;
                } else {
                    content.master_no = config.setting.OperatingArea;
                }
            }

            $rootScope.menuList = menuItem.childs;
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.favourite_machine_info_get',
                content : content,
                success : function(data){
                    $rootScope.hideMenu();
                    
                    if(!menuItem.default && menuItem.childs.length > 0){
                        const _defaultItem = menuItem.childs.shift();
                        menuItem.default = _defaultItem.name;
                    }
                    if(data.query_restult.length > 0){
                        $rootScope.changeProgram(menuItem.default, {machine_list : data.query_restult});
                    } else {
                        $rootScope.changeProgram('B0214_F', {data:{
                            parent:'home',
                            next:menuItem.default,
                            master_no:content.master_no,
                            machine_list:[]
                        }});
                    }
                }
            });
        };

        RouterExtendProvider.loadReportModule = function(menuItem, callback){
            userCustomReportGet(function(data){
                if(data.report_info && data.report_info.length>0){
                    // 20231115 modify by Alan for#0149444 : 修正自訂義報表載入，以菜單配置為準，若未配置菜單，則以userCustomReportGet為準
                    const childs = data.report_info
                        .map((item, index) => {
                            let matchNode = menuItem.childs.find(child => child.name === item.report_id)
                            return {
                                name: item.report_id,
                                displayText: matchNode ? matchNode.displayText : item.report_description,
                                color: '#e6b800',
                                icon: matchNode ? matchNode.icon : 'W_Com_User_Edit_nor_32',
                                isShow: matchNode ? matchNode.isShow : true,
                                order: matchNode ? matchNode.order : index,
                                isReport: true
                            }
                        })
                    if(typeof callback === 'function') {
                        //menuItem.childs = (menuItem.childs||[]).concat(childs);
                        menuItem.childs = childs;
                        callback(menuItem);
                    } else {
                        $rootScope.changeProgram(childs[0].name, {data:{
                            is_report:true,
                            report_name:childs[0].title,
                            outside_url:config.cache.sys_parameter.FRURL
                        }});
                        if(childs.length > 1){
                            $rootScope.loadMenu(childs);
                        }
                    }
                } else {
                    $rootScope.showAlert($filter('translate')('C12.msg.user_define_report_not_set'));
                }
            });
        };
        RouterExtendProvider.loadKanbanModule = function(menuItem, callback){
            userCustomKanbanGet(function(data){
                if(data.kanban_management_info && data.kanban_management_info.length > 0)
                {
                    // 20231115 modify by Alan for#0149444 : 修正看板管理載入，以菜單配置為準，若未配置菜單，則以userCustomReportGet為準
                    const childs = data.kanban_management_info
                        .map((item, index) => {
                            let matchNode = menuItem.childs.find(child => child.name === item.report_id)
                            return {
                                name: item.report_id,
                                displayText: matchNode ? matchNode.displayText : item.report_description,
                                color: '#e6b800',
                                icon: matchNode ? matchNode.icon : 'W_Com_Board_nor_32',
                                isShow: matchNode ? matchNode.isShow : true,
                                order: matchNode ? matchNode.order : index,
                                isReport: true
                            }
                        })
                    if(typeof callback === 'function') {
                        //menuItem.childs = (menuItem.childs||[]).concat(childs);
                        menuItem.childs = childs;
                        callback(menuItem);
                    } else {
                        $rootScope.changeProgram(childs[0].name, {data:{
                            is_report:true,
                            report_name:childs[0].title,
                            outside_url:config.cache.sys_parameter.FRURL
                        }});
                        if(childs.length > 1){
                            $rootScope.loadMenu(childs);
                        }
                    }
                }
                else
                {
                    $rootScope.showAlert($filter('translate')('C12.msg.user_kanban_report_not_set'));
                }
            })
        }

        //20221021 modify by wangzy for M#0120911: H5端管理看板，只有DS可以查看，群组权限中找不到对应的权限分配
        RouterExtendProvider.loadReportModuleNew = function (menuItem, callback) {
            userCustomReportGet(function (data) {
                if (data.report_info && data.report_info.length > 0) {
                    // 20231115 modify by Alan for#0149444 : 修正自訂義報表載入，以菜單配置為準，若未配置菜單，則以userCustomReportGet為準
                    const childs = data.report_info
                        .map((item, index) => {
                            let matchNode = menuItem.childs.find(child => child.name === item.report_id)
                            return {
                                name: item.report_id,
                                displayText: matchNode ? matchNode.displayText : item.report_description,
                                color: '#e6b800',
                                icon: matchNode ? matchNode.icon : 'W_Com_User_Edit_nor_32',
                                isShow: matchNode ? matchNode.isShow : true,
                                order: matchNode ? matchNode.order : index,
                                isReport: true
                            }
                        })
                    if (typeof callback === 'function') {
                        //menuItem.childs = (menuItem.childs||[]).concat(childs);
                        menuItem.childs = childs;
                        callback(menuItem);
                    } else {
                        $rootScope.changeProgram(childs[0].name, {
                            data: {
                                is_report: true,
                                report_name: childs[0].title,
                                outside_url: config.cache.sys_parameter.FRURL
                            }
                        });
                        if (childs.length > 1) {
                            $rootScope.loadMenu(childs);
                        }
                    }
                }
            });
        };
        RouterExtendProvider.loadKanbanModuleNew = function (menuItem, callback) {
            //20221130 modify by wangzy for M#0123318: 该员工登录MES前台总是显示：请先设定帆软站台，其他员工没有这个报错
            userCustomKanbanGetNew(function (data) {
                if (data.kanban_management_info && data.kanban_management_info.length > 0) {
                    // 20231115 modify by Alan for#0149444 : 修正看板管理載入，以菜單配置為準，若未配置菜單，則以userCustomReportGet為準
                    const childs = data.kanban_management_info
                        .map((item, index) => {
                            let matchNode = menuItem.childs.find(child => child.name === item.report_id)
                            return {
                                name: item.report_id,
                                displayText: matchNode ? matchNode.displayText : item.report_description,
                                color: '#e6b800',
                                icon: matchNode ? matchNode.icon : 'W_Com_Board_nor_32',
                                isShow: matchNode ? matchNode.isShow : true,
                                order: matchNode ? matchNode.order : index,
                                isReport: true
                            }
                        })
                    if (typeof callback === 'function') {
                        //menuItem.childs = (menuItem.childs||[]).concat(childs);
                        menuItem.childs = childs;
                        callback(menuItem);
                    } else {
                        $rootScope.changeProgram(childs[0].name, {
                            data: {
                                is_report: true,
                                report_name: childs[0].title,
                                outside_url: config.cache.sys_parameter.FRURL
                            }
                        });
                        if (childs.length > 1) {
                            $rootScope.loadMenu(childs);
                        }
                    }
                }
            })
        }


        RouterExtendProvider.loadReportProgram = function(menuItem, callback){
            // 20230222 modify by Alan for M#0128751: 配合報表新開視窗功能調整
            if(config.setting.externalWindow === 'Y') {
                $rootScope.OpenProgramWindow(menuItem);
            } else {
                // 20230210 modify by Alan for#127517 : 修正自訂義報表載入
                $rootScope.changeProgram(menuItem.name, {data:{
                    is_report:true,
                    report_name:$filter('translate')(menuItem.displayText).replace('<br>', ''),
                    outside_url:config.cache.sys_parameter.FRURL
                }});
            }
            if(!menuItem.hideMenu && menuItem.childs && $filter('filter')(menuItem.childs, {isShow:true}).length>1){
                $rootScope.loadMenu(menuItem.childs);
            } else {
                $rootScope.hideMenu();
            }
        }

        RouterExtendProvider.showLogging = function(){
            $LoggingService.init();
        };

        // 增加左下角的按鈕
        RouterExtendProvider.GetSideTools = function(){
            return RouterExtendProvider.sideTools;
        };

        // 增加側邊欄清單的擴充功能
        // 使用遞迴方式載入模板
        RouterExtendProvider.addExtendSideMenu = function(scope, sideMenuTemp, sideExtendTemp, callback){
            addExtendSideMenu(0, scope, sideMenuTemp, sideExtendTemp, callback);
        };

        function addExtendSideMenu(index, scope, sideMenuTemp, sideExtendTemp, callback){
            if(index < RouterExtendProvider.extendSideMenus.length){
                try{
                    scope = RouterExtendProvider.extendSideMenus[index].genController(scope);
                    RouterExtendProvider.extendSideMenus[index].genTemplate(sideMenuTemp, sideExtendTemp, function(sideMenuTemp, sideExtendTemp){
                        addExtendSideMenu(index+1, scope, sideMenuTemp, sideExtendTemp, callback);
                    });
                }catch(e){
                    console.error(e);
                    addExtendSideMenu(index+1, scope, sideMenuTemp, sideExtendTemp, callback);
                }
            } else if(typeof(callback) === 'function'){
                callback(scope, sideMenuTemp, sideExtendTemp);
            }
        }

        // 20240131 modify by shiwl for M#0157012: 穎宸6.0:版更6009後H5報表類均開啟錯誤，無法執行
        function backCloseWindow (callback, errorback){
            $rootScope.closeAllWindow();
            $timeout(function(){
                var paramets = {data:{notLogin:true}};
                paramets.beforeExist = function(callback){
                    $rootScope.selectHome = true;
                 
                    config.mdssessionno = '';
                    if(config.cache.autoLogin){
                        try{
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            remote.getCurrentWindow().close();
                        } catch(e){
                            nodeRequire('nw.gui').Window.get().close();
                        }
                    } else {
                        $rootScope.subMenu = undefined;
                        $rootScope.hideMenu();
                    }
                    callback();

                };
                if(typeof callback == 'function')
                    paramets.beforeExist(callback);
                else
                    $rootScope.changeProgram(RouterExtendProvider.login_page, paramets, true);
            });
        }
        //20190226 modify by Dustdusk for M#0055209: 連線U數問題
        if(window.nodeRequire){
			window.addEventListener('beforeunload', function(e){
				if(config.mdssessionno != undefined && config.mdssessionno != ''){
                    if(RouterExtendProvider != undefined){

                        if(localStorage.getItem('sJDS_login') == undefined){
                            event.returnValue = false;
                            $rootScope.closeAllWindow();
                               
                            if(config.setting.externalWindow =='Y') {
                                backCloseWindow(function(){
                                    window.close();
                                })
                              
                            } else {
                                RouterExtendProvider.logout(function(){
                                    window.close();
                                }, function(){
                                    window.close();
                                });
                            }
                          
                        }
                    }
                }
			});
        }

        //使用者自訂報表
        function userCustomReportGet(callback){
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.user_custom_report_info_get',
                content : {},
                success : function(data){
                    callback(data);
                }
            });
        }
        //M#94634 查詢使用者自定義看板
        function userCustomKanbanGet(callback){
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.user_kanban_management_info_get',
                content : {},
                success : function(data){
                    callback(data);
                }
            });
        }
        function userCustomKanbanGetNew(callback) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.user_kanban_management_info_get',
                content: {},
                success: function (data) {
                    callback(data);
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }
        return RouterExtendProvider;
    }]);
});
